#include <QDir>
#include "SequenceManager.h"
#include "Sequences.pb.h"

SequenceManager::SequenceManager() :
   Plugin(),
   theSequenceWorker(NULL),
   theNumberLeds(0)
{
   // Blank intentionally
}

Plugin* SequenceManager::getPlugin()
{
   return this;
}

void SequenceManager::importSequences()
{
   QDir directory(DIR_FTP_DATA, QString("*" + EXT_SEQ));

   // Data files exist in directory
   if(directory.count() > 0)
   {
      foreach(QString fileName, directory.entryList())
      {
         QFile file(directory.path() + QDir::separator() + fileName);
         parseSequence(file);
      }
   }
   else
   {
      qCritical() << "No sequence data files found in" << directory.path();
   }
}

void SequenceManager::parseSequence(QFile &file)
{/*
   if(file.exists() && file.open(QIODevice::ReadOnly))
   {
      Sequence sequence;
      quint32 lineNumber = 0;

      while(!file.atEnd())
      {
         QString line = file.readLine();
         QStringList cells = line.split(",");

         quint32 led = cells.value(0).toUInt();
         QColor color(cells.value(1).toUInt(), cells.value(2).toUInt(), cells.value(3).toUInt());
         quint32 delayMs = cells.value(4).toUInt();

         if((led < theNumberLeds) && (color.red() < 0x80) && (color.green() < 0x80) && (color.blue() < 0x80))
         {
            sequence.addEntry(Entry(led, color, delayMs));
         }
         else
         {
            qWarning() << "Invalid sequence entry at line number" << lineNumber << "in" << file.fileName();
         }

         lineNumber++;
      }

      theSequenceWorker->addSequence(sequence);
   }
   else
   {
      qCritical() << file.fileName() << "failed to open:" << file.errorString();
   }*/
}

void SequenceManager::slotStartService()
{
   QVariant value;
   emit signalGetConfigValue(KEY_NUM_LEDS, value);
   theNumberLeds = value.toUInt();

   theSequenceWorker = new SequenceWorker();
   connect(theSequenceWorker, SIGNAL(signalSetColor(quint32,QColor)), this, SIGNAL(signalSetColor(quint32,QColor)));

   importSequences();
}

void SequenceManager::slotStopService()
{
   theSequenceWorker->quit();
   theSequenceWorker->wait();
   theSequenceWorker->deleteLater();
}

void SequenceManager::slotConfigUpdate(const QString &key,
                                       QVariant &value)
{
   if(key == KEY_NUM_LEDS)
   {
      theNumberLeds = value.toUInt();
   }
}

void SequenceManager::slotEventNotification(Event event)
{
   Q_UNUSED(event)
   // Blank intentionally
}

Q_EXPORT_PLUGIN(SequenceManager)
